import { onInitialized, storageStore } from '@shared/context'
import { sendTabMessage } from '@shared/serverMessage'
import { ContextMenuId, PostMessageType } from '@shared/types'
import { computed, watch } from 'vue'

const menuList: { id: ContextMenuId; title: string; origin?: boolean }[] = [
  { id: ContextMenuId.OPEN_OPTIONS, title: '打开配置页' },
  { id: ContextMenuId.MARKE_AS_SWAGGER, title: '标记为 Swagger' },
  { id: ContextMenuId.PREVIEW, title: '查看', origin: true },
  { id: ContextMenuId.CLIPBOARD_WRITE_TEXT, title: '写入粘贴板', origin: true },
  { id: ContextMenuId.CONSOLE_GROUP, title: 'console.group', origin: true },
  { id: ContextMenuId.CONSOLE_GROUP_COOLAPSED, title: 'console.groupCollapsed', origin: true }
]

export const docsApiMatch = computed(() => {
  return storageStore.docsApis.map(({ origin }) => {
    return `${origin}/*`
  })
})

onInitialized(() => {
  const parentId = chrome.contextMenus.create({
    id: 'swagger2dts',
    title: 'swagger2dts'
  })

  const defaultMatch = [...docsApiMatch.value]

  menuList.forEach(({ id, title, origin }) => {
    chrome.contextMenus.create({
      id,
      title,
      parentId,
      visible: !origin || !!defaultMatch.length,
      documentUrlPatterns: origin ? defaultMatch : void 0
    })
  })

  watch(docsApiMatch, (matchs) => {
    menuList.forEach(({ id, origin }) => {
      origin &&
        chrome.contextMenus.update(id, {
          visible: !!matchs.length,
          documentUrlPatterns: matchs
        })
    })
  })
})

chrome.contextMenus.onClicked.addListener((info, tab) => {
  switch (info.menuItemId) {
    case ContextMenuId.OPEN_OPTIONS: {
      chrome.runtime.openOptionsPage()
      break
    }
    case ContextMenuId.MARKE_AS_SWAGGER: {
      sendTabMessage(tab?.id, { type: PostMessageType.CONNECT, data: '' })
      sendTabMessage(tab?.id, { type: PostMessageType.CONTEXT_MENU, data: info.menuItemId })
      break
    }
    case ContextMenuId.PREVIEW:
    case ContextMenuId.CONSOLE_GROUP:
    case ContextMenuId.CONSOLE_GROUP_COOLAPSED:
    case ContextMenuId.CLIPBOARD_WRITE_TEXT: {
      sendTabMessage(tab?.id, { type: PostMessageType.CONTEXT_MENU, data: info.menuItemId })
      break
    }
  }
})
